package com.example.scene;

import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.example.fruit.GameActivity;
import com.example.input.topscore;
import com.example.manager.PauseableTimerHandler;
import com.example.manager.ResourcesManager;
import com.example.manager.SceneManager;

import android.app.ProgressDialog;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;

public class ServerScore {
	private static String SOAP_ACTION = "http://tempuri.org/updateScore";
	private static String METHOD_updateScore = "updateScore";
	
	private static String SOAP_ACTION1 = "http://tempuri.org/checkScore";
	private static String METHOD_checkScore = "checkScore";
	
	private static String SOAP_ACTIONLOADSCORE = "http://tempuri.org/loadscore";
	private static String METHOD_LOADSCORE = "loadscore";

	private static String NAMESPACE = "http://tempuri.org/";
	private static String URL = "http://serviceninja.somee.com/servicehighscore.asmx?wsdl";
	GameActivity activity;
	ResultScene rs;
	public ServerScore()
	{
		activity=ResourcesManager.getInstance().activity;
	}
	
	public void updateScore()
	{
		updateHighScore task=new updateHighScore();
		task.execute();
	}
	static boolean checkupdate;
	boolean flagupdate=false;
	class updateHighScore extends AsyncTask<Void, Void, String>
	{
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			activity.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					activity.showDialog(8);
				}
			});
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			SoapObject request = new SoapObject(NAMESPACE, METHOD_updateScore);
			
			// Use this to add parameters
			SharedPreferences login = activity.getSharedPreferences("login", activity.MODE_PRIVATE);
			SharedPreferences.Editor loginEditor = login.edit();
			String user=login.getString("user", "unknow!");
			int score = Integer.parseInt(GameScene.score);
			
			request.addProperty("username", user);
			request.addProperty("score", score);
			
			// Declare the version of the SOAP request
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			String s ="";
			envelope.setOutputSoapObject(request);
			envelope.dotNet = true;
			try {
				HttpTransportSE androidHttpTransport = new HttpTransportSE(
						URL);

				// this is the actual part that will call the webservice
				androidHttpTransport.call(SOAP_ACTION, envelope);
				
				// Get the SoapResult from the envelope body.
				SoapObject result = (SoapObject) envelope.bodyIn; //the loadscoreresponse
				if(result!=null){
					s=result.getProperty(0).toString();	
				}
				;
			} catch (Exception e) {
				e.printStackTrace();
				//Log.d("asdad",e.getMessage());
			}
			return s;
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(result.equals("true"))
			{
				activity.dismissDialog(8);
				activity.message=null;
				activity.message="Cập nhật thành công điểm lên server!";
				activity.showDialog(4);
			}else{
				activity.dismissDialog(8);
				activity.message=null;
				activity.message="Điểm hiện tại nhỏ hơn điểm mà bạn đã cập nhật trước đây!";
				activity.showDialog(4);
			}
			this.cancel(true);
		}

	}
	PauseableTimerHandler p;
	int checkscore;
	public void checkScore()
	{	
		rs=(ResultScene) SceneManager.getInstance().getCurrentScene();
		checkHighScore task=null;
		task=new checkHighScore();
		task.execute();
		p=new PauseableTimerHandler(0.5f, true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				// TODO Auto-generated method stub
				if(flag){
					p.mPause=true;
					p.setAutoReset(false);
					ResourcesManager.getInstance().engine.unregisterUpdateHandler(p);
					if(check)
						checkscore=1;
					else
						checkscore=2;
				}
				Log.d("checkscore",checkscore+"");
			}
		});
		ResourcesManager.getInstance().engine.registerUpdateHandler(p);
	}
	
	static boolean check;
	boolean flag=false;
	boolean touch1=true;
	class checkHighScore extends AsyncTask<Void, Void, String>
	{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			touch1=false;
			activity.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					
					// TODO Auto-generated method stub
					rs.waiting();
				}
			});
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			SoapObject request = new SoapObject(NAMESPACE, METHOD_checkScore);
			
			// Use this to add parameters
			int score = Integer.parseInt(GameScene.score);
			request.addProperty("score", score);
			
			// Declare the version of the SOAP request
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			String s ="";
			envelope.setOutputSoapObject(request);
			envelope.dotNet = true;
			try {
				HttpTransportSE androidHttpTransport = new HttpTransportSE(
						URL);

				// this is the actual part that will call the webservice
				androidHttpTransport.call(SOAP_ACTION1, envelope);
				
				// Get the SoapResult from the envelope body.
				SoapObject result = (SoapObject) envelope.bodyIn; //the loadscoreresponse
				if(result!=null){
					s=result.getProperty(0).toString();	
				}
				;
			} catch (final Exception e) {
				activity.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						activity.message=null;
						activity.message=e.getMessage();
						activity.showDialog(4);
					}
				});
			}
			return s;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			this.cancel(true);
			activity.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					rs.unwaiting();
					touch1=true;
				}
			});
			
			if(result.equals("true"))
			{
				check=true;
			}else
			{
				check=false;
			}
			flag=true;
			
		}
	}
	HighScores hs;
	boolean touch=true;
	public void showHighScore()
	{
		try {
			hs=(HighScores) SceneManager.getInstance().getCurrentScene();
			loadHighScore task=new loadHighScore();
			task.execute();
		} catch (Exception e) {
			// TODO: handle exception
			activity.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					activity.message=null;
					activity.message="khong the load diem!";
					activity.showDialog(4);
				}
			});
		}
		
	}
	
	public static boolean clickHighScore;
	class loadHighScore extends AsyncTask<Void, Void, String>
	{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			touch=false;
			activity.runOnUiThread( new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					hs.waiting();
				}
			});
		}
		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			SoapObject request = new SoapObject(NAMESPACE, METHOD_LOADSCORE);
			String s = "";
			// Declare the version of the SOAP request
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);

			envelope.setOutputSoapObject(request);
			envelope.dotNet = true;
			try {
				HttpTransportSE androidHttpTransport = new HttpTransportSE(
						URL);

				// this is the actual part that will call the webservice
				androidHttpTransport.call(SOAP_ACTIONLOADSCORE, envelope);

				// Get the SoapResult from the envelope body.
				SoapObject result = (SoapObject) envelope.getResponse(); //the loadscoreresponse
				
				if (result != null) {
					topscore[] lsscores;
					lsscores=RetrieveFromSoap(result);
					
					for (topscore sc : lsscores) {
						s+=sc._stt+": "+sc._name+" -- "+sc._score+"\n";
					}

					Log.d("danhsach",s);
				} else {
					activity.error="No Response";
					activity.showDialog(2);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return s;
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			activity.dsscore=result;
				activity.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						hs.unwaiting();
						activity.showDialog(1);
						Log.d("showDialog","showDialog");
						touch=true;
					}
				});
				this.cancel(true);
		}

	}
	public static topscore[] RetrieveFromSoap(SoapObject soap) {
		topscore[] categories = new topscore[soap.getPropertyCount()];

		for (int i = 0; i < categories.length; i++) {
			SoapObject pii = (SoapObject) soap.getProperty(i);//anyType
			topscore category = new topscore();
			category._stt = Integer.parseInt(pii.getProperty(0).toString());
			category._name = pii.getProperty(1).toString();
			category._score = Integer.parseInt(pii.getProperty(2).toString());
			categories[i] = category;
		}
		return categories;
	}
}
